package com.le.tester.javaThink.fifth.chapter14_StreamingProgramming;

import java.util.Optional;
import java.util.function.Consumer;
import java.util.stream.Stream;

/**
 * 描述：optional中的函数
 */
public class OptionalsSelf {
    static void basics(Optional<String> optionalS) {
        if (optionalS.isPresent())
            System.out.println(optionalS.get());
        else
            System.out.println("Nothing inside");

    }

    static void ifPresent(Optional<String> optionalS) {
        optionalS.ifPresent(System.out::println);
    }

    static void orElse(Optional<String> optionalS) {
        System.out.println(optionalS.orElse("Nana"));
    }

    static void orElseGet(Optional<String> optionalS) {
        System.out.println(optionalS.orElseGet(() -> "generated"));
    }

    static void orElseThrow(Optional<String> optionalS) {
        try {
            System.out.println(optionalS.orElseThrow(() -> new Exception("supplied")));
        } catch (Exception e) {
            System.out.println("Caught " + e);
        }
    }

    static void test(String testName, Consumer<Optional<String>> cos) {
        System.out.println("====" + testName + "====");
        cos.accept(Stream.of("Epithets").findFirst());
        cos.accept(Stream.<String>empty().findFirst());
    }

    public static void main(String[] args) {
        test("basics ", OptionalsSelf::basics);
        test("ifPresent ", OptionalsSelf::ifPresent);
        test("orElse ", OptionalsSelf::orElse);
        test("orElseGet", OptionalsSelf::orElseGet);
        test("orElseThrow", OptionalsSelf::orElseThrow);
    }
}
